package com.yao.springredisdemo.config;

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.yao.springredisdemo.entity.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis的配置类
 * @author yao
 */
@Configuration
public class RedisConfig {
    /**
     * 默认使用的连接工厂是lettuce，默认情况下所有的分阻塞和非事务的操作所使用的连接实例都使用同一个线程安全的本地连接。不推荐使用,
     * 要想使用jedis作为连接工厂 需要导入jedis的包,然后maven将lettuce包去掉
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String, Student> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String, Student> redisTemplate = new RedisTemplate<>();
        // 设置连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 设置value的序列化方式
        FastJsonRedisSerializer<Student> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Student.class);
        redisTemplate.setValueSerializer(fastJsonRedisSerializer);
        // 设置key的序列化方式
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}
